package com.example.schoolblog.blog.Controller;


import com.example.schoolblog.blog.Dto.AccessTokenDto;
import com.example.schoolblog.blog.Dto.UserDto;
import com.example.schoolblog.blog.Dto.UserTokenDTO;
import com.example.schoolblog.blog.Model.User;
import com.example.schoolblog.blog.Provider.GiteeProvider;
import com.example.schoolblog.blog.Service.UserService;
import com.example.schoolblog.blog.utils.JWTUtil;
import com.example.schoolblog.blog.utils.RedisService;
import com.example.schoolblog.blog.utils.RedisServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
@Slf4j
public class AuthorizeController {

    //@Autowired
    //private GithupProvider githupProvider;

    @Autowired
    private GiteeProvider giteeProvider;
    @Autowired
    private UserService userService;

    @Value("${client_id}")
    private String client_id;
    @Value("${client_secret}")
    private String client_secret;
    @Value("${redirect_uri}")
    private String redirect_uri;


    //主页点击登录，经gitee携带code和state跳转到此请求，
    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code")String code,
                           @RequestParam(name = "state")String state,
                           HttpServletRequest request,
                           HttpServletResponse response) {

        //将第三方返回的信息封装到AccessTokenDto类中
        AccessTokenDto accessTokenDto = new AccessTokenDto();
        accessTokenDto.setCode(code);
        accessTokenDto.setState(state);
        accessTokenDto.setClientId(client_id);
        accessTokenDto.setClientSecret(client_secret);
        accessTokenDto.setRedirectUri(redirect_uri);
        //调用giteeProvider.getAccessToken获取token
        //String access_token = githupProvider.getAccessToken(accessTokenDto);
        String access_token = giteeProvider.getAccessToken(accessTokenDto);

        //利用获取到的token调用giteeProvider.getUser获取gitee用户的信息
        //GithupUser githupUser = githupProvider.getUser(access_token);
        UserDto userDto = giteeProvider.getUser(access_token);

        //获取到用户信息后，将用户信息封装到user用户对象中，并插入数据库
        if(userDto != null && userDto.getId() != null){
            User dbuser = new User();
            //String token = UUID.randomUUID().toString();
            UserTokenDTO userTokenDTO = new UserTokenDTO();
            userTokenDTO.setAccountId(String.valueOf(userDto.getId()));
            userTokenDTO.setAvatarUrl(userDto.getAvatarUrl());
            userTokenDTO.setGmtCreate(System.currentTimeMillis());
            userTokenDTO.setName(userDto.getName());
            String token = JWTUtil.generateToken(userTokenDTO);
            //将token存在redis缓存中
            RedisService service = new RedisServiceImpl();
            service.set(String.valueOf(userDto.getId()),token);


            dbuser.setAccountId(String.valueOf(userDto.getId()));
            dbuser.setAvatarUrl(String.valueOf(userDto.getId()));
            dbuser.setName(userDto.getName());
            dbuser.setAvatarUrl(userDto.getAvatarUrl());
            dbuser.setToken(token);
            //插入或更新数据库，因为用户信息会变，修复用户重复问题
            userService.createOrupdate(dbuser);
            //将cookie：token返回给浏览器
            Cookie cookie = new Cookie("token",token);
            cookie.setMaxAge(60 * 60 * 24);
            //防止xss攻击
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            return "redirect:/";
        }else{
            log.error("callback get github error,{}", userDto);
            return "redirect:/";
        }
    }

    //退出登录
    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response){
        //移除服务端的session
        request.getSession().removeAttribute("user");
        //将token置为null
        Cookie cookie = new Cookie("token",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }

}
